﻿// --------------------------------------------------------------------------------------------------------------------
// <copyright file="Nhibernate.cs" company="Rabi Dog Labs">
//   Rabid Dog Labs
// </copyright>
// <summary>
//   Nhibernate session wrapper
// </summary>
// --------------------------------------------------------------------------------------------------------------------

using System;
using System.Reflection;
using TeamCommunitySolution.Domain.DataLayer;

namespace TeamCommunitySolution.Repositories.Providers
{
    /// <summary>
    /// Nhibernate session wrapper
    /// </summary>
    public class Nhibernate
    {
        /// <summary>
        /// internal holder.
        /// </summary>
        private static NHibernate.Cfg.Configuration _cfg = null;

        /// <summary>
        /// internal holder.
        /// </summary>
        private static NHibernate.ISessionFactory _sessionFactory = null;

        /// <summary>
        /// Gets the factory.
        /// </summary>
        /// <value>The factory.</value>
        public static NHibernate.ISessionFactory Factory
        {
            get
            {
                if (_cfg == null)
                {
                    _cfg = GetConfig();
                }

                if (_sessionFactory == null)
                {
                    _sessionFactory = _cfg.BuildSessionFactory();
                }

                return _sessionFactory;
            }
        }

        /// <summary>
        /// Gets the config.
        /// </summary>
        /// <returns>NHibernate Configuration</returns>
        private static NHibernate.Cfg.Configuration GetConfig()
        {
            _cfg = new NHibernate.Cfg.Configuration();
            _cfg.Configure();

            string location = Assembly.GetAssembly(typeof(ConfigurationPointer)).Location;

            if (!System.IO.File.Exists(location))
            {
                throw new Exception("Unable to find the hibernate data definition in the NHSessionFactory");
            }

            _cfg.AddAssembly(Assembly.LoadFrom(location));

            return _cfg;
        }
    }
}
